"""
__author__ = '霍格沃兹测试开发学社'
__desc__ = '更多测试开发技术探讨，请访问：https://ceshiren.com/t/topic/15860'
"""
# 导入 flask 和 flask_sqlalchemy
from flask import Flask, request
from flask_restx import Resource, Api, Namespace
from flask_sqlalchemy import SQLAlchemy
# 实例化app 对象
from sqlalchemy import *

app = Flask(__name__)
api = Api(app)
case_ns = Namespace("case manager", description="用例管理")

username = "root"
pwd = "123456"
ip = "42.192.73.147"
port = "3306"
database = "test_server"

app.config['SQLALCHEMY_DATABASE_URI'] = \
    f"mysql+pymysql://{username}:{pwd}@{ip}:{port}/{database}?charset=utf8"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# SQLAlchemy 绑定 app
db = SQLAlchemy(app)

# 用例表
class TestCase(db.Model):
    # 用例ID，用例的唯一标识
    id = db.Column(Integer, primary_key=True)
    # 用例的标题或者文件名
    case_title = db.Column(String(80), unique=True, nullable=False)
    # 备注
    remark = db.Column(String(120))

# case_ns.route添加的是子路由
@case_ns.route("")
class TestCaseServer(Resource):
    get_parser = api.parser()
    get_parser.add_argument('id', type=int, location="args")
    @case_ns.expect(get_parser)
    def get(self):
        """
        测试用例的查找
        :return:
        """
        case_id = request.args.get("id")
        print(case_id)
        if case_id:
            case_data = TestCase.query.filter_by(id=case_id).first()
            print(f"case_data--{case_data}")
            if case_data:
                datas = [{"id": case_data.id,
                          "case_title": case_data.case_title,
                          "remark": case_data.remark,
                          }]
            else:
                datas = []

        else:
            case_datas = TestCase.query.all()
            print(f"case_datas--{case_datas}")
            datas = [{"id": case_data.id, "node_id": case_data.case_title, "remark": case_data.remark} for case_data in
                     case_datas]

        print(f"返回的数据为：{datas}")
        return datas

    post_parser = api.parser()
    post_parser.add_argument('id', type=int, location="json", required=True)
    post_parser.add_argument('case_title', type=str, location="json", required=True)
    post_parser.add_argument('remark', type=str, location="json")
    # 通过 expect() 传递参数
    @case_ns.expect(post_parser)
    def post(self):
        """
        测试用例的新增
        :return:
        """
        case_data = request.json
        print(case_data)
        # 请求的数据
        case_id = case_data.get("id")
        exist = TestCase.query.filter_by(id=case_id).first()
        print(exist)
        # 判断这个id是否存在
        # 如果存在 则报40001错误码
        # 如果不存在 则将这条添加到数据库中
        if not exist:
            # 创建数据库实例
            testcase = TestCase(**case_data)
            db.session.add(testcase)
            db.session.commit()
            return {"code": 0, "msg": f"case id {case_id} success add .", "res":case_data}
        else:
            return {"code": 40001, "msg": f"case is exist.", "res":case_data}

    put_parser = api.parser()
    put_parser.add_argument('id', type=int, location="json", required=True)
    put_parser.add_argument('case_title', type=str, location="json", required=True)
    put_parser.add_argument('remark', type=str, location="json")
    # 通过 expect() 传递参数
    @case_ns.expect(put_parser)
    def put(self):
        """
        测试用例的修改
        :return:
        """
        case_data = request.json
        print(case_data)
        case_id = case_data.get("id")
        exist = TestCase.query.filter_by(id=case_id).first()
        if exist:
            case_data["case_title"] = case_data.get("case_title")
            case_data["remark"] = case_data.get("remark")
            TestCase.query.filter_by(id=case_id).update(case_data)
            db.session.commit()
            return {"code": 0, "msg": f"case id {case_id} success change to {case_data}", "res":case_data}
        else:
            return {"code": 40002, "msg": "case is not exist", "res":case_data}

    delete_parser = api.parser()
    delete_parser.add_argument('id', type=int, location="args", required=True)
    # 通过 expect() 传递参数
    @case_ns.expect(delete_parser)
    def delete(self):
        """
        测试用例的删除
        :return:
        """
        case_data = request.args
        print(case_data)
        case_id = case_data.get("id")
        exist = TestCase.query.filter_by(id=case_id).first()
        print(exist)
        if exist:
            TestCase.query.filter_by(id=case_id).delete()
            db.session.commit()
            return {"code": 0, "msg": f"Case id {case_id} success delete", "res":case_data}
        else:
            return {"code": 40002, "msg": "case is not exist", "res":case_data}

# 绑定 方法与路由 的关联
api.add_namespace(case_ns, '/testcase')

if __name__ == '__main__':
    # db.create_all()
    app.run(debug=True)